<?php

namespace zhtfrontend\models\datas;

use common\components\extenders\MenuManage;
use common\components\helpers\Fun;
use common\models\datas\Cate;
use common\models\datas\Customer;
use common\models\datas\Student;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%customer_return_visit}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $status
 * @property string $mobile
 * @property integer $created_at
 * @property string $details
 * @property string $results
 * @property integer $admin_id
 * @property integer $category_id
 * @property integer $relationship_id
 */
class CustomerReturnVisit extends \zhtfrontend\components\bases\BaseModel
{
    public $student;
    public $buy;
    public $is_customer;
    public $change_status;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%customer_return_visit}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status', 'admin_id', 'category_id', 'relationship_id', 'site_id', 'type','change_status','interviewer_id','next_interviewer_id'], 'integer'],
            [['name', 'mobile', 'details', 'created_at', 'results', 'next_time'], 'string', 'max' => 255],
            [['mobile'], 'check_mobile'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('zhtfrontend', '自增id'),
            'name' => Yii::t('zhtfrontend', '客户姓名'),
            'status' => Yii::t('zhtfrontend', '状态'),
            'mobile' => Yii::t('zhtfrontend', '客户联系方式'),
            'details' => Yii::t('zhtfrontend', '回访详情'),
            'results' => Yii::t('zhtfrontend', '处理结果'),
            'admin_id' => Yii::t('zhtfrontend', '负责人id'),
            'category_id' => Yii::t('zhtfrontend', '意向分类id'),
            'created_at' => Yii::t('zhtfrontend', '回访时间'),
            'type' => Yii::t('zhtfrontend', '回访方式'),
            'site_id' => Yii::t('zhtfrontend', '分店id'),
            'next_time' => Yii::t('zhtfrontend', '下次回访时间'),
            'relationship_id' => Yii::t('zhtfrontend', 'customer_relationship id'),
            'interviewer_id' => Yii::t('zhtfrontend', '当前约谈人'),
            'next_interviewer_id' => Yii::t('zhtfrontend', '下次约谈人'),
            'follow_status' => Yii::t('zhtfrontend', '跟进状态'),
            'change_status' => Yii::t('zhtfrontend', '是否转化'),
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['next_time'] = function () {
            return \Yii::$app->formatter->asDatetime($this->next_time);
        };

        $fields['type'] = function () {
            switch ($this->type) {
                case '0':
                    return \Yii::t('zhtfrontend', '电话');
                case '1':
                    return \Yii::t('zhtfrontend', '约谈');
                case '2':
                    return \Yii::t('zhtfrontend', '其他');
            }
        };

        $fields['status'] = function () {
            switch ($this->status) {
                case '0':
                    return \Yii::t('zhtfrontend', '潜在客户');
                case '1':
                    return \Yii::t('zhtfrontend', '意向客户');
                case '2':
                    return \Yii::t('zhtfrontend', '意向可转化客户');
                case '3':
                    return \Yii::t('zhtfrontend', '普通会员');
                case '4':
                    return \Yii::t('zhtfrontend', '正式VIP');
                case '':
                    return \Yii::t('zhtfrontend', '意向客户');
            }
        };

        $fields['maturity'] = function () {
            //$title='不明确';

            if (isset($this->maturity)) {
                switch ($this->maturity) {
                    case 'A+':
                        return \Yii::t('zhtfrontend', '明确成交意向');
                    case 'A-':
                        return \Yii::t('zhtfrontend', '有初步成交意向');
                    case 'B+':
                        return \Yii::t('zhtfrontend', '初步联系，有意向');
                    case 'B-':
                        return \Yii::t('zhtfrontend', '初步联系，意向不确定');
                    case 'C':
                        return \Yii::t('zhtfrontend', '无效客户');
                    case 'D':
                        return \Yii::t('zhtfrontend', '初步联系，有意向');
                }
            } else {
                $customer = Customer::find()->where(['mobile' => $this->mobile, 'site_id' => $this->site_id])->one();
                if (isset($customer)) {
                    $orders = (new Query())->select('*')->from('{{%orders}}')->where(['customer_id' => $customer->id])->all(Fun::getSiteDb());
                }
                return (isset($orders)) ? \Yii::t('zhtfrontend', '明确成交意向') : \Yii::t('zhtfrontend', '有初步成交意向');
            }

            $category = Cate::findOne(['id' => $this->category_id]);
            return $category->name;
        };

        $fields['category_id'] = function () {
            $category = Cate::findOne(['id' => $this->category_id]);
            return $category->name;
        };

        $fields['admin_id'] = function () {
            $admin = Admin::findOne(['id' => $this->admin_id]);
            return $admin->name;
        };
        $fields['interviewer_id'] = function () {
            $title = '暂无';
            if (!empty($this->interviewer_id)) {
                $admin = Admin::findOne(['id' => $this->interviewer_id]);
                if (isset($admin)) {
                    $title = $admin->name;
                }
            } else {
                $admin = Admin::findOne(['id' => $this->admin_id]);
                if (isset($admin)) {
                    $title = $admin->name;
                }
            }
            return $title;
        };
        $fields['next_interviewer_id'] = function () {
            $title = '暂无';
            if (!empty($this->next_interviewer_id)) {
                $admin = Admin::findOne(['id' => $this->next_interviewer_id]);
                if (isset($admin)) {
                    $title = $admin->name;
                }
            } else {
                $admin = Admin::findOne(['id' => $this->admin_id]);
                if (isset($admin)) {
                    $title = $admin->name;
                }
            }
            return $title;
        };

        $fields['is_customer'] = function () {
            $customer = Customer::find()->where(['mobile' => $this->mobile, 'site_id' => $this->site_id])->one();
            $is_customer = (isset($customer)) ? '已注册' : '未注册';
            return $is_customer;
        };

        $fields['is_student'] = function () {
            $is_student = '没绑定';
            $customer = Customer::find()->where(['mobile' => $this->mobile, 'site_id' => $this->site_id])->one();
            if (isset($customer)) {
                $student = Student::find()->where(['customer_id' => $customer->id])->asArray()->all();
                if (isset($student)) {
                    $is_student = '绑定' . count($student) . '位学员';
                }
            }
            return $is_student;
        };

        $fields['is_buy'] = function () {
            $is_buy = '否';
            $customer = Customer::find()->where(['mobile' => $this->mobile, 'site_id' => $this->site_id])->one();
            if (isset($customer)) {
                $orders = (new Query())->select('*')->from('{{%orders}} o')->leftJoin('{{%orders_items_relation}} oir', 'o.id=oir.orders_id')
                    ->where(['oir.customer_id' => $customer->id])->all(Fun::getSiteDb());
                if (isset($orders)) {
                    $is_buy = '是';
                }
            }
            return $is_buy;
        };

        $fields['follow_status'] = function () {
            switch ($this->follow_status) {
                case '0':
                    return \Yii::t('zhtfrontend', '可跟进');
                case '1':
                    return \Yii::t('zhtfrontend', '不可跟进');
                case '3':
                    return \Yii::t('zhtfrontend', '已回收');
            }
        };
        return $fields;
    }

    public function extraFields()
    {
        return [
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
            },
        ];
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'next_time'],

                ],
            ],

        ]);
    }

    public function check_mobile($attribute)
    {
        $is_mobile = "/^1[34578]{1}\d{9}$/";
        if (strlen($this->$attribute) == 11) {
            $customer_relationship = CustomerRelationship::find()->where(['mobile' => $this->$attribute, 'site_id' => Fun::getSiteId()])->one();
            if (isset($customer_relationship)) {
                if (!preg_match($is_mobile, $this->$attribute)) {
                    $this->addError($attribute, Yii::t('zhtfrontend', '手机号码格式不合法!'));
                } else {
                    if($this->name!==$customer_relationship->name){
                        $this->addError($attribute, Yii::t('zhtfrontend', '会员姓名和电话号码不对应!'));
                    }else{
                        $return_visit = CustomerReturnVisit::find()->where(['mobile' => $this->$attribute])->one();
                        if(\Yii::$app->user->identity->role!='sales_director'){
                            if($customer_relationship->salesman_id!=\Yii::$app->user->id){
                                if (isset($return_visit) && $return_visit->follow_status == 1) {
                                    $this->addError($attribute, Yii::t('zhtfrontend', '您不能操作该手机号对应的会员!'));
                                }
                            }

                        }
                    }
                }
            } else {
                $this->addError($attribute, Yii::t('zhtfrontend', '手机号码和会员信息不匹配!'));
            }
        } else {
            $this->addError($attribute, Yii::t('zhtfrontend', '手机号码格式不合法!'));
        }
    }
}
